package com.tangyuan.live.util;

import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.DescribeLiveStreamPublishedListRequest;
import com.tencentcloudapi.live.v20180801.models.DescribeLiveStreamPublishedListResponse;
import com.tencentcloudapi.live.v20180801.models.StreamName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class LiveUtil {

    @Value("${live.pushDomainName:}")
    String pushDomainName;
    @Value("${live.playDomainName:}")
    String playDomainName;
    @Value("${live.agreement:}")
    String agreement;
    @Value("${live.pushKey:}")
    String pushKey;
    @Value("${live.playKey:}")
    String playKey;
    @Value("${live.secretId:}")
    String secretId;
    @Value("${live.secretKey:}")
    String secretKey;

    public String joinLivePushUrl(Long userId){
        return agreement + pushDomainName + "/live/" + userId+"?"+getSafeUrl( pushKey, userId.toString() , System.currentTimeMillis());
    }

    public String joinLivePlayUrl(Long userId){
        return agreement + playDomainName + "/live/" + userId+"?"+getSafeUrl(playKey , userId.toString() , System.currentTimeMillis());
    }

    public StreamName[] getStreamName(Date createTime){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("live.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            LiveClient client = new LiveClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DescribeLiveStreamPublishedListRequest req = new DescribeLiveStreamPublishedListRequest();
            req.setDomainName(pushDomainName);
            req.setEndTime(format.format(new Date()));
            req.setStartTime(format.format(createTime));
            // 返回的resp是一个DescribeLiveStreamPublishedListResponse的实例，与请求对象对应
            DescribeLiveStreamPublishedListResponse resp = client.DescribeLiveStreamPublishedList(req);
            // 输出json格式的字符串回包
            String jsonString = AbstractModel.toJsonString(resp);
            DescribeLiveStreamPublishedListResponse response = AbstractModel.fromJsonString(jsonString, DescribeLiveStreamPublishedListResponse.class);
            return response.getPublishInfo();
        } catch (TencentCloudSDKException e) {
            log.error("获取历史直播流失败,异常:{}",e.toString());
        }
        return null;
    }


    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /*
     * KEY+ streamName + txTime
     */
    private static String getSafeUrl(String key, String streamName, long txTime) {
        String input = new StringBuilder().
                append(key).
                append(streamName).
                append(Long.toHexString(txTime).toUpperCase()).toString();

        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret  = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }
    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];

        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }



}
